from flask import current_app
from flask import g, jsonify
from flask import request
from flask import session

from ihome import db
from ihome.modules.api import api_blu
from ihome.utils.common import check, file_upload

# 获取用户信息
from ihome.utils.response_code import RET, error_map


# 获取个人信息
@api_blu.route('/user', methods=['GET'])
@check
def get_user_info():
    user = g.user

    if not user:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=user.to_dict())


# 上传头像
@api_blu.route('/user/avatar', methods=['POST'])
@check
def upload_image():
    print(g.user)
    user = g.user

    avatar = request.files.get('avatar')
    if not avatar:
        return jsonify(RET.PARAMERR, error_map[RET.PARAMERR])

    # POST 提交数据
    img_file = request.files.get("avatar")
    # 读取文件的二进制数据
    try:
        img_bytes = img_file.read()

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 一般文件的存取会使用文件服务器来操作, 上传文件成功后, 只需要该文件的访问URL即可
    try:
        file_name = file_upload(img_bytes)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])
    # 记录头像URL
    user.avatar_url = file_name

    db.session.add(user)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(RET.DBERR, error_map[RET.DBERR])

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=user.to_dict())


# 修改用户名
@api_blu.route('/user/name', methods=['POST', 'GET'])
@check
def change_username():
    user = g.user

    # 接受参数
    name = request.json.get('name')
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 业务处理,修改用户名
    user.name = name
    session['name'] = name
    db.session.add(user)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 获取/修改实名信息
@api_blu.route('/user/auth', methods=['GET', 'POST'])
@check
def get_real_info():
    user = g.user

    if request.method == 'GET':
        return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=user.to_auth_info())
    # 获取信息
    # 接收数据
    real_name = request.json.get('real_name')
    id_card = request.json.get('id_card')

    if not all([real_name, id_card]):
        return jsonify(RET.PARAMERR, error_map[RET.PARAMERR])
    # 修改实名信息
    user.real_name = real_name
    user.id_card = id_card

    db.session.add(user)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
